package cn.hdmis.util;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.hdmis.security.dao.UserDao;
import cn.hdmis.security.entity.User;

public class SysRealm extends AuthorizingRealm{
	@Resource
	private UserDao userDao;
	private AccountManager accountManager;
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	/**
	 * 授权信息
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
				PrincipalCollection principals) {
		/**
		String username=(String)principals.fromRealm(getName()).iterator().next();
		if( username != null ){
			User user = accountManager.get( username );
			if( user != null && user.getRoles() != null ){
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				for( Role role: user.getRoles() ){
						info.addRole(role.getName());
						//info.addStringPermissions(role.getPermissionsAsString());
				}
				return info;
			}
		}**/
		return null;
	}

	/**
	 * 认证信息
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
				AuthenticationToken authcToken ) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		String password = String.valueOf(token.getPassword());
		if( userName != null && !"".equals(userName.toString())&&password != null && !"".equals(password.trim()) ){
			User user = new User();
			user.setLogonid(userName);
			user.setPassword(password);
			List<User> list = userDao.findByEntity(user);
			if(list.size()>0){
				SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(userName,password,getName());
				return sai;
			}else{
				throw new UnknownAccountException();
			}
		}
		return null;
	}


}